--[[
TrashyFu - a FuBar plugin for removing unwanted vendor trash from your inventory

version: 1.2
author: Tabithy
email: tabithy@gmail.com
website: http://www.googlecode.com/p/tabstools
]]

local tablet = AceLibrary("Tablet-2.0")
local abacus = AceLibrary("Abacus-2.0")
local itemPrice = AceLibrary("ItemPrice-1.1")

local cleanable = {}

local emptySlots = 0

TrashyFu = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0", "AceDB-2.0", "FuBarPlugin-2.0")

TrashyFu:RegisterDB("TrashyFuDB")
TrashyFu:RegisterDefaults('profile', {sound=true, autoClean=false})

TrashyFu.emptyIcon = "trash_empty.tga"
TrashyFu.filledIcon = "trash_filled.tga"

TrashyFu.ignoredBags = {["Ammo Pouch"]=true, ["Quiver"]=true, ["Enchanting Bag"]=true, ["Engineering Bag"]=true, 
		["Gem Bag"]=true, ["Herb Bag"]=true, ["Mining Bag"]=true, ["Soul Bag"]=true, ["Leatherworking Bag"]=true}

TrashyFu.hasIcon = true
TrashyFu.cannotDetachTooltip = true
TrashyFu.defaultPosition = "RIGHT"

TrashyFu.options = {
	type = 'group',
		args = {
		clean = {
			name="Clean",
			desc="Remove a piece of |cff9d9d9dvendor trash|r from your bags",
			type='execute',
			func="Clean"
		}, 
		sound = {
			name="Sound",
			desc="Turn on sound effects",
			type='toggle',
			get=function () return TrashyFu.db.profile.sound end,
			set=function (v) TrashyFu.db.profile.sound = v end
		},
		autoClean = {
			name="Auto-Clean",
			desc="Automatically remove excess |cff9d9d9dvendor trash|r from your bags as you loot it",
			type='toggle',
			get=function() return TrashyFu.db.profile.autoClean end,
			set=function(v) TrashyFu.db.profile.autoClean = v end
		},
	}
}

TrashyFu.OnMenuRequest = TrashyFu.options
TrashyFu:RegisterChatCommand({"/trashyfu"}, TrashyFu.options)

function TrashyFu:ScanBags()
	cleanable = {}
	emptySlots =  0
	local useable
	for bag = 0, 4 do
		if bag >= 1 then
			local bagLink = GetInventoryItemLink("player",ContainerIDToInventoryID(bag))
			if (bagLink) then 
				_, _, _, _, _, _, subtype = GetItemInfo(bagLink)
				useable = (not TrashyFu.ignoredBags[subtype])
			else
				useable = false
			end
		end
		if (bag == 0 or useable) then
			for slot = 1, GetContainerNumSlots(bag) do
				local link = GetContainerItemLink(bag, slot)
				if (link) then
					local name, _, rarity, _, _, itype = GetItemInfo(link)
					local _, count = GetContainerItemInfo(bag, slot)
					if (rarity == 0) then
						local value = itemPrice:GetPrice(link) * count                        
						local item = {bag=bag, slot=slot, link=link, name=name, count=count, value=value}
						cleanable[#cleanable + 1] = item
					end
				else 
					emptySlots = emptySlots + 1
				end
			end
		end
	end
	table.sort(cleanable, function (a,b) return (a.value < b.value) end)
end


function TrashyFu:Clean()
	if (#cleanable > 0) then
		if (MerchantFrame:IsVisible()) then
			self:SellItems()
		else
			self:DeleteItem()
		end
	else
		self:Print("nothing to clean")
	end
end


function TrashyFu:AutoClean()
	if (emptySlots == 0 and #cleanable > 0) then
		self:DeleteItem()
	end
end


function TrashyFu:DeleteItem()
	local item = cleanable[1]
	PickupContainerItem(item.bag, item.slot)
	DeleteCursorItem()
	table.remove(cleanable, 1)
	local feedback = "trashed " .. item.link
	if (item.count > 1) then
		feedback = feedback .. "x" .. item.count
	end
	if item.value then
		feedback = feedback .. " worth " .. abacus:FormatMoneyFull(item.value, true)
	end
	self:Print(feedback)
	if (TrashyFu.db.profile.sound) then
		PlaySoundFile([[Interface\AddOns\FuBar_TrashyFu\clean.wav]])
	end
end


function TrashyFu:SellItems()
	local value = 0
	local number = #cleanable
	for index, item in ipairs(cleanable) do 
		UseContainerItem(item.bag, item.slot)
		value = value + item.value
	end
	self:Print("sold "..number.." items for "..abacus:FormatMoneyFull(value, true))
end


function TrashyFu:UpdateIcon()
	if #cleanable > 0 then
		self:SetIcon(TrashyFu.filledIcon)
	else
		self:SetIcon(TrashyFu.emptyIcon)
	end
end


function TrashyFu:BAG_UPDATE()
	self:ScanBags()
	self:UpdateIcon()
	self:UpdateText()
	if TrashyFu.db.profile.autoClean then
		self:AutoClean()
	end
end


function TrashyFu:OnEnable()
	self:RegisterBucketEvent("BAG_UPDATE", 1)
	self:ScanBags()
	self:UpdateIcon()
	self:UpdateText()
end


function TrashyFu:OnDoubleClick()
	self:Clean()
end


function TrashyFu:OnTooltipUpdate()
	local cat = tablet:AddCategory('columns', 2,
		'child_textR', 1,
        	'child_textG', 1,
        	'child_textB', 0,
        	'child_text2R', 1,
        	'child_text2G', 1,
		'child_text2B', 1
	)
	for i, item in ipairs(cleanable) do
		local name = "|cff9d9d9d" .. item.name .. "|r" .. ((item.count > 1) and (" x" .. item.count) or "")       
		cat:AddLine(
			'text', name,
			'text2', ((item.value ~= 0) and abacus:FormatMoneyFull(item.value, true) or "???")
		)
	end
	tablet:SetHint("double click to remove the least valuable piece of |cff9d9d9dvendor trash|r from your inventory, or, if you are at a merchant, sell all the trash in your inventory")
end


function TrashyFu:OnTextUpdate()
	if (#cleanable > 0) then
		self:SetText("" .. #cleanable )
	else
		self:SetText("")
	end
end


-- Colorize string with the appropriate color for the given item quality level
function TrashyFu:Colorize(string, quality)
	if (not quality) then quality = 1 end
	_, _, _, hex = GetItemQualityColor(quality)
	return hex .. string .. "|r"
end
